package game.module.qzmj.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import db.proto.ProtoMessageQzmj.ARound;
import db.proto.ProtoMessageQzmj.AllAction;
import db.proto.ProtoMessageQzmj.ByteArray;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;

import game.module.qzmj.QzmjConstants;
import game.module.qzmj.bean.QzmjRound;
import game.module.qzmj.logic.QzmjDatamanager;
import game.module.qzmj.logic.QzmjEstimateUserRespondHelper;
import game.module.qzmj.logic.QzmjLogic;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageQzmj.S2CQzmjChupai;
import lua.LuaMessageQzmj.C2SQzmjChupai;
import lua.LuaMessageQzmj.PushQzmjChupai;
import lua.LuaMessageQzmj.PushQzmjStatetoALL;
@MsgCodeAnn(msgcode = C2SQzmjChupai.id, accessLimit = 500)
public class QzmjChupaiProcessor extends PlayingRoleMsgProcessor{

	private static Logger logger = LoggerFactory.getLogger(QzmjChupaiProcessor.class);
	
	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		// TODO Auto-generated method stub
		
		long startMili = System.currentTimeMillis();
		C2SQzmjChupai reqMsg = C2SQzmjChupai.parse(request);
		byte cbCardData = reqMsg.pai;
		int playerId = playingRole.getId();
		logger.info("out cards={} player={}",cbCardData,playerId);
		S2CQzmjChupai respMsg = new S2CQzmjChupai((short) 0,(short)0);// 当前是否是我的回合
		final QzmjRound mjround = QzmjDatamanager.getInstance().getMjRoom(playerId);
		int m_wCurrentUser = mjround.getPlayerIds().indexOf(playerId);
		int wChairID = mjround.getM_wCurrentUser();
		byte cardIndex[][] = mjround.getCardIndex();
		assert (wChairID == m_wCurrentUser);
		assert (QzmjLogic.getInstance().IsValidCard(cbCardData) == true);
		if (wChairID !=m_wCurrentUser) {
			respMsg.is_success = 1;// 当前不是我的回合
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		if (QzmjLogic.getInstance().IsValidCard(cbCardData) == false) {
			respMsg.is_success = 3; // 牌的信息有误
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		if (QzmjLogic.getInstance().RemoveCard(cardIndex[wChairID], cbCardData) == false) {
			logger.info("failed remove cbCardData ={},",cbCardData);
			S2ErrorCode resp = new S2ErrorCode(501); //扣除手牌失败
			playingRole.writeAndFlush(resp.build(playingRole.alloc()));
			assert (false);
			return;
		}
		List<Byte> pushcard = mjround.getPushed_card().get(m_wCurrentUser);
		logger.info("out cards={}",pushcard);
		pushcard.add(cbCardData);//玩家出过的牌
		// 设置变量
		byte[] m_cbUserAction = mjround.getM_cbUserAction();
		byte[] m_cbPerformAction = mjround.getM_cbPerformAction();
		boolean[] m_bTianDiHu = mjround.getM_bTianDiHu();
		mjround.setM_bSendStatus(true);
		mjround.setM_bGangStatus(false);
		m_cbUserAction[wChairID] = QzmjConstants.WIK_NULL;
		m_cbPerformAction[wChairID] = QzmjConstants.WIK_NULL;
		m_bTianDiHu[wChairID] = true;
		// 出牌记录
		mjround.setM_cbOutCardData(cbCardData);
		mjround.setM_wOutCardUser(wChairID); // 记录出牌玩家 和打出的手牌
		List<Byte> singCardEye = mjround.getSingCardEye().get(m_wCurrentUser);
		boolean[] singlegold = mjround.getSingGold();
		boolean [] doublegold = mjround.getDoubleGold();
		boolean [] threegold = mjround.getThreeGold();
		if(doublegold[m_wCurrentUser] == true && cbCardData == mjround.getGod_card()) {
			threegold[m_wCurrentUser] = true;
			doublegold[m_wCurrentUser] = false;
		}else {
			doublegold[m_wCurrentUser] = false;
		}
		
		if(singlegold[m_wCurrentUser] ==true && cbCardData == mjround.getGod_card()) {
			doublegold[m_wCurrentUser] = true;
			singlegold[m_wCurrentUser] = false;
		}else {
			singlegold[m_wCurrentUser] = false;
		}
		
		if(!singCardEye.isEmpty()) {
			if(singCardEye.contains(cbCardData)) //打出对子中非金牌
				singlegold[m_wCurrentUser] = true;
		}
		ARound thisaround = mjround.getARound();
		ARound.Builder moAround = thisaround.toBuilder();
		AllAction.Builder thisAction = AllAction.newBuilder();
		thisAction.setUserAction(QzmjConstants.battle_chupai);
		thisAction.setPlayerIndex(m_wCurrentUser);
		thisAction.addOperatorCards(cbCardData);
		moAround.addActions(thisAction);
		ARound moderound = moAround.build();
		mjround.setARound(moderound);
		if(singlegold[m_wCurrentUser] || doublegold[m_wCurrentUser] || threegold[m_wCurrentUser]) {
			ARound thisround = mjround.getARound();
			ARound.Builder msoAround = thisround.toBuilder();
			AllAction.Builder aAction = AllAction.newBuilder();
			PushQzmjStatetoALL pushall = new PushQzmjStatetoALL();
			if(singlegold[m_wCurrentUser]) {
				pushall.type = 1;
				aAction.setUserAction(QzmjConstants.battle_youjin);	
			}
			if(doublegold[m_wCurrentUser]) {
				pushall.type = 2;
				aAction.setUserAction(QzmjConstants.battle_shuangyou);
			}
			if(threegold[m_wCurrentUser]) {
				pushall.type = 3;
				aAction.setUserAction(QzmjConstants.battle_sanyou);
			}
			logger.info("youjin={}",pushall.type);
			pushall.index =(byte)m_wCurrentUser;
			List<Integer> playerIds = mjround.getPlayerIds();
			for (Integer aPlayer : playerIds) {
				PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayer);
				if (pr != null && pr.isChannelActive()) {
					pr.writeAndFlush(pushall.build(pr.alloc()));
					// 推送关于出牌的信息
				}
			}
			msoAround.addActions(aAction);
			ARound mderound = msoAround.build();
			mjround.setARound(mderound);
		}

		if(doublegold[m_wCurrentUser]||singlegold[m_wCurrentUser]||threegold[m_wCurrentUser])
			respMsg.is_glod = 1;
		else
			respMsg.is_glod = 0;
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));//告诉成功
		
		PushQzmjChupai pushMsg = new PushQzmjChupai();
		pushMsg.chupai_player_index = (short) m_wCurrentUser;
		pushMsg.pai = cbCardData;
		List<Integer> playerIds = mjround.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
				// 推送关于出牌的信息
			}
		}
		byte cbCardCount = QzmjLogic.getInstance().GetCardCount(cardIndex[m_wCurrentUser]);
		logger.info("mj chu pai playerid={},pai={},Cards_num={}",playerId,pushMsg.pai,cbCardCount);
    	if (mjround.getRemain_card().size() <= 16) {
    		QzmjLogic.getInstance().OnEventGameConclude(true,mjround);
    		return ; //游戏结束
		}
		m_wCurrentUser = m_wCurrentUser + 1;
		if(m_wCurrentUser>=4)
			m_wCurrentUser=0;
		mjround.setM_wCurrentUser(m_wCurrentUser);
		boolean[] m_bEnjoinChiHu = mjround.getM_bEnjoinChiHu();
		if(cbCardData == mjround.getGod_card()) {//金牌打出
		    for(int m = 0;m<m_bEnjoinChiHu.length;m++) {
		    	if(m==m_wCurrentUser)
		    		continue;
		    	m_bEnjoinChiHu[m] = true;
		    }
		}
		
		if(m_bEnjoinChiHu[m_wCurrentUser]==true) {
			m_bEnjoinChiHu[m_wCurrentUser] = false;
		}
		for(byte[] aplayer:cardIndex ) {
			if(aplayer[QzmjLogic.getInstance().SwitchToCardIndex(mjround.getGod_card())]>=1) {
				QzmjEstimateUserRespondHelper.getInstance().analycardHelp((byte) wChairID, cbCardData, QzmjConstants.EstimatKind_OutCard, mjround,m_wCurrentUser);
				return;
			}
		}
		boolean bAroseAction = QzmjLogic.getInstance().EstimateUserRespond(wChairID, cbCardData,QzmjConstants.EstimatKind_OutCard, mjround);
		mjround.setM_wResumeUser(m_wCurrentUser);
		if (bAroseAction == false) {
			QzmjLogic.getInstance().DispatchCardData(m_wCurrentUser, true, mjround);
		}
		logger.info("cost time = {}ms",System.currentTimeMillis()-startMili);
	}

	public boolean GuardFeng(byte carddata,byte currentUser,final boolean[] canFeng ,byte godCard,final byte cardindex[]) {
		return true;

	} 
	
	public void ZeroMemory(byte[] array) {
		for (int i = 0; i < array.length; i++) {
			array[i] = 0;
		}
	}

	public void ZeroMemory(boolean[] array) {
		for (int i = 0; i < array.length; i++) {
			array[i] = false;
		}
	}

	public void setFollowFeng(byte CurrentUser,QzmjRound mjrond,byte carddata) {
		return;
	}
	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
